﻿using System;
using System.Runtime.InteropServices;
using System.Security;

namespace IntoNails.Infrastructure.Security
{
    public static class SecurityStringHelper
    {
        public static SecureString ToSecureString(this string input)
        {
            SecureString secureString = new SecureString();
            foreach (char c in input)
            {
                secureString.AppendChar(c);
            }

            secureString.MakeReadOnly();

            return secureString;
        }

        public static string ToUnsecureString(this SecureString securePassword)
        {
            if (securePassword == null)
            {
                throw new ArgumentNullException("securePassword");
            }

            IntPtr intPtr = IntPtr.Zero;
            string result;

            try
            {
                intPtr = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                result = Marshal.PtrToStringUni(intPtr);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(intPtr);
            }

            return result;
        }
    }
}
